package _base0to1;

/**
 * 707. 设计链表
 */
public class No707 {
    private MyNode head;

    public No707() {
        head = new MyNode();
        head.val = -1;
    }

    public int get(int index) {
        MyNode cur = head;
        for (int i = 0; i <= index; i++) {
            if (cur.next == null) return -1;
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        MyNode cur = new MyNode();
        cur.val = val;
        cur.next = head.next;
        head.next = cur;
    }

    public void addAtTail(int val) {
        MyNode newNode = new MyNode(val, null);
        MyNode cur = head;
        while (cur.next != null) cur = cur.next;
        cur.next = newNode;
    }

    public void addAtIndex(int index, int val) {
        MyNode newNode = new MyNode(val, null);
        MyNode cur = head;
        for (int i = 0; i < index; i++) {
            if (cur.next == null) return;
            cur = cur.next;
        }
        newNode.next = cur.next;
        cur.next = newNode;
    }

    public void deleteAtIndex(int index) {
        MyNode cur = head;
        for (int i = 0; i < index; i++) {
            if (cur.next == null) return;
            cur = cur.next;
        }
        if (cur.next != null) cur.next = cur.next.next;
    }

    private class MyNode {
        int val;
        MyNode next;

        public MyNode() {
        }

        public MyNode(int val, MyNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
